package com.infodms.dms.actions.sales.marketmanage.planissued;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.common.FileUploadManager;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.getCompanyId.GetOemcompanyId;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.sales.marketmanage.planissued.ActivitiesPlanIssuedDao;
import com.infodms.dms.dao.sales.planmanage.SpacePlanManageDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TmOrgPO;
import com.infodms.dms.po.TtCampaignExecutePO;
import com.infodms.dms.po.TtCampaignGroupRPO;
import com.infodms.dms.po.TtCampaignPO;
import com.infodms.dms.po.TtCampaignSpaceExecutePO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

public class ActivitiesSpacePlanMake {
	public Logger logger = Logger.getLogger(ActivitiesPlanMake.class);   
	SpacePlanManageDao dao  = SpacePlanManageDao.getInstance();
	private ActionContext act = ActionContext.getContext();
	RequestWrapper request = act.getRequest();
	private final String initUrl = "/jsp/sales/marketmanage/planissued/ActivitiesSpacePlanQuery.jsp";
	private final String detailUrl = "/jsp/sales/marketmanage/planissued/activitiesSpacePlanDetails.jsp";
	private final String modelUrl = "/jsp/sales/marketmanage/planissued/activitiesModelQuery.jsp";
	private final String dealerAttachUrl ="/jsp/sales/marketmanage/planissued/activitiesDealerAndAttach.jsp";
	
	// 修改页面
	private final String modifyUrl = "/jsp/sales/marketmanage/planissued/activitiesPlanMakeUpdate.jsp";
	
	// 下发范围选择经销商页面
	private final String dealerSelUrl ="/jsp/sales/marketmanage/planissued/selectDealer.jsp";
	/**
	 * 活动方案制定页面初始化
	 */
	public void activitiesPlanMakeInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			act.setOutData("areaList", areaList);
			act.setForword(initUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动方案制定页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}

	/**
	 * 活动信息查询
	 */
	public void activitiesPlanQuery(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		//logonUser.getOrgId();
		try {
			Long orgId=logonUser.getOrgId();
			Long poseId = logonUser.getPoseId() ;
			String areaId=request.getParamValue("areaId");//业务范围ID
			String campaignNo = request.getParamValue("campaignNo");			//方案编号
			String campaignName = request.getParamValue("campaignName");		//方案名称
			String campaignSubject = request.getParamValue("campaignSubject");	//活动主题
			String campaignType = request.getParamValue("campaignType");		//活动类别
			String startDate = request.getParamValue("startDate");				//开始时间
			String endDate = request.getParamValue("endDate");					//结束时间
			//String checkStatus =request.getParamValue("checkStatus");			//方案状态
			String dealerCode = request.getParamValue("dealerCode");			//经销商CODE
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps = dao.activitiesQuery(poseId, areaId,orgId,campaignNo, campaignName, campaignSubject, campaignType, startDate, endDate, dealerCode, curPage, Constant.PAGE_SIZE);
			act.setOutData("ps", ps);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动信息查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 活动信息明细查询
	 */
	public void activitiesPlanQueryDetail(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			act.setOutData("areaList", areaList);
			//执行方案下发的经销商Id
			//String[] dlrIds = request.getParamValues("dlrIds");  
			String campaignId = request.getParamValue("campaignId");
			String executeId = request.getParamValue("executeId");
			Map<String, Object> map2 = dao.activitiesInfoQuery(campaignId, executeId);
			String modelName = dao.getModelName(campaignId);
			map2.put("PROD_NAME", modelName);
			//通过活动方案id查询活动方案信息
			Map<String, Object> compaignMap = dao.getCompaignPlanById(campaignId);
			List<Map<String, Object>> executePlans = dao.getMyExecutePlanByCmpId(campaignId);
			TtCampaignExecutePO executePo=new TtCampaignExecutePO();
			executePo.setCampaignId(Long.parseLong(campaignId));
			Map<String, Object> list1= dao.getExecuteInfo(campaignId);
			//Map<String, Object> map3 = dao.activitiesTargetQuery(executeId);
			//List<Map<String, Object>> list1 = dao.getActivitiesCostbyId(executeId, campaignId);
			//List<Map<String, Object>> list2 = dao.getActivitiesMediaCost(executeId);
			//List<Map<String, Object>> list3 = dao.getCheckInfo(executeId);
			//List<Map<String, Object>> list4 = dao.getAttachInfo(executeId);
			List<Map<String, Object>> list4 = dao.getAttachInfo(campaignId);
			//List<Map<String, Object>> list5 = dao.getZJCheckInfo(executeId);
			act.setOutData("map3",list1);
			act.setOutData("compaignMap", compaignMap);
			act.setOutData("executePlans", executePlans);
			act.setOutData("list4", list4);
			act.setOutData("map2", map2);
			act.setForword(detailUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动信息明细查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/*
	 * 获取机构详细信息
	 */
	public void getAllOrgs(){
		String orgCode=request.getParamValue("orgCode");
		String[] list=orgCode.split(",");
		List myList=new ArrayList();
		TmOrgPO po=new TmOrgPO();
		po.setOrgCode(orgCode);
		TmOrgPO tmOrgPo=new TmOrgPO();
		for(int i=0;i<list.length;i++){
			tmOrgPo=(TmOrgPO) dao.select(po).get(i);
			myList.add(tmOrgPo);
		}
		act.setOutData("myList",myList);
	}
	/**
	 * 活动方案制定的修改保存（用于长安汽车）
	 */
	@SuppressWarnings("unchecked")
	public void updateExecutePlan(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		
		try{
			String campaignId = CommonUtils.checkNull(request.getParamValue("campaignId"));
			String execAddDesc=request.getParamValue("execAddDesc");//活动地点说明
			String adviceDesc=request.getParamValue("adviceDesc");//建议以及整改措施
			TtCampaignExecutePO myPo1 = new TtCampaignExecutePO();
			myPo1.setCampaignId(Long.parseLong(campaignId));
			TtCampaignExecutePO myPo2 = new TtCampaignExecutePO();
			if(execAddDesc!=""&&execAddDesc!=null){
				myPo2.setExecAddDesc(execAddDesc);
			}
			if(adviceDesc!=null&&adviceDesc!=""){
				myPo2.setAdviceDesc(adviceDesc);
			}
			if(execAddDesc!=""&&adviceDesc!=""&&execAddDesc!=null&&adviceDesc!=null){
			dao.update(myPo1,myPo2);
			}
			//页面删除的经销商id
			String delDlrIds = CommonUtils.checkNull(request.getParamValue("delDlrIds"));        
			String delDealers = delDlrIds.replaceFirst(",", "");
			String [] delDlrArr = delDealers.split(",");
			if(null!=delDlrArr&&0!=delDlrArr.length){
				for(int i=0;i<delDlrArr.length;i++){
					if(!"".equals(delDlrArr[i])){
						deleteExecutePlanByRow(campaignId,delDlrArr[i]);
					}
				}
			}
			
			//执行方案下发的经销商Id
			String[] dlrIds = request.getParamValues("dlrIds");
			Long orgId = logonUser.getOrgId() ;
			String executeId ="";
			if(null!=dlrIds&&dlrIds.length>0){
				for(int i=0;i<dlrIds.length;i++){
					// 查询执行方案表中是否存在该经销商的数据
					List<Map<String, Object>> executePlans = dao.getExecutePlanByCmpId(campaignId,dlrIds[i]);
					
					//如果不存在插入
					if(null==executePlans||0==executePlans.size()){
						TtCampaignExecutePO po = new TtCampaignExecutePO();
						executeId = SequenceManager.getSequence(""); 
						po.setExecuteId(new Long(executeId));
						po.setCampaignId(new Long(campaignId));
						po.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_12);
						po.setCreateBy(logonUser.getUserId());
						po.setCreateDate(new Date(System.currentTimeMillis()));
						po.setDealerId(new Long(dlrIds[i]));
						po.setExecAddDesc(execAddDesc);
						po.setAdviceDesc(adviceDesc);
						po.setOrgId(orgId) ;
						dao.addExecutePlan(po);
					}
				}
			}
			act.setOutData("returnValue", 1);
			
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.UPDATE_FAILURE_CODE,"活动方案修改");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 修改页面中删除经销商
	 */
	public void deleteExecutePlanByRow(String campaignId,String dealerId){
		
			// 通过传参查询出相关记录
			List<Map<String, Object>> executePlans = dao.getExecutePlanByCmpId(campaignId,dealerId);
			
			Map<String, Object> map = executePlans.get(0);
			
			// 取得执行方案id
			String executeId = map.get("EXECUTE_ID").toString();
			
			// 删除
			TtCampaignExecutePO po = new TtCampaignExecutePO();
			po.setExecuteId(Long.parseLong(executeId));
			
			dao.delExecutePlan(po);
			
	}
	/**
	 * 修改页面中的下发(用于长安汽车)
	 */
	@SuppressWarnings("unchecked")
	public void assignExecutePlan(){
		String execAddDesc=request.getParamValue("execAddDesc");//活动地点说明
		String adviceDesc=request.getParamValue("adviceDesc");//建议以及整改措施
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		
		try{
			 String campaignId = CommonUtils.checkNull(request.getParamValue("campaignId"));                 //活动方案id
			
			//页面删除的经销商id
			String delDlrIds = CommonUtils.checkNull(request.getParamValue("delDlrIds"));        
			String delDealers = delDlrIds.replaceFirst(",", "");
			String [] delDlrArr = delDealers.split(",");
			if(null!=delDlrArr&&0!=delDlrArr.length){
				for(int i=0;i<delDlrArr.length;i++){
					if(!"".equals(delDlrArr[i])){
						deleteExecutePlanByRow(campaignId,delDlrArr[i]);
					}
				}
			}
			
			//页面删除的附件
			String delAttachs = CommonUtils.checkNull(request.getParamValue("delAttachs"));       
			String delAttachIds = delAttachs.replaceFirst(",", "");
			String [] delAttachArr = delAttachIds.split(",");
			if(null!=delAttachArr&&0!=delAttachArr.length){
				for(int i=0;i<delAttachArr.length;i++){
					FileUploadManager.delfileUploadByBusiness(delAttachArr[i], logonUser);
				}
			}
			
			//执行方案下发的经销商Id
			String[] dlrIds = request.getParamValues("dlrIds"); 
			Long orgId = logonUser.getOrgId() ;
			//附件ID
			String []fjids = request.getParamValues("fjids");				             
			String executeId ="";
			if(null!=dlrIds&&dlrIds.length>0){
				for(int i=0;i<dlrIds.length;i++){
					// 查询执行方案表中是否存在该经销商的数据
					List<Map<String, Object>> executePlans = dao.getExecutePlanByCmpId(campaignId,dlrIds[i]);
					
					//如果不存在插入
					if(null==executePlans||0==executePlans.size()){
						executeId = SequenceManager.getSequence(""); 
						TtCampaignSpaceExecutePO mypo=new TtCampaignSpaceExecutePO();
						mypo.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_01);
						TtCampaignSpaceExecutePO mypo1=new TtCampaignSpaceExecutePO();
						mypo1.setOrgId(logonUser.getOrgId());
						mypo1.setCampaignId(Long.parseLong(campaignId));
						dao.update(mypo1, mypo);
						TtCampaignExecutePO po = new TtCampaignExecutePO();
						
						po.setExecuteId(new Long(executeId));
						po.setCampaignId(new Long(campaignId));
						po.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_02);
						// po.setCreateBy(logonUser.getUserId());
						po.setCreateDate(new Date(System.currentTimeMillis()));
						po.setDealerId(new Long(dlrIds[i]));
						po.setAdviceDesc(adviceDesc);
						po.setExecAddDesc(execAddDesc);
						po.setOrgId(orgId) ;
						dao.addExecutePlan(po);
						
					}else{
						TtCampaignSpaceExecutePO mypo=new TtCampaignSpaceExecutePO();
						mypo.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_01);
						TtCampaignSpaceExecutePO mypo1=new TtCampaignSpaceExecutePO();
						mypo1.setOrgId(logonUser.getOrgId());
						mypo1.setCampaignId(Long.parseLong(campaignId));
						//mypo1.setSpaceId(new Long(executeId));
						dao.update(mypo1, mypo);
						TtCampaignExecutePO po1 = new TtCampaignExecutePO();
						TtCampaignExecutePO po2 = new TtCampaignExecutePO();
						//executeId = SequenceManager.getSequence(""); 
					//	po.setExecuteId(new Long(executeId));
						po1.setCampaignId(new Long(campaignId));
						po2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_02);
						//po.setCreateBy(logonUser.getUserId());
						//po.setCreateDate(new Date(System.currentTimeMillis()));
						po1.setDealerId(new Long(dlrIds[i]));
						po2.setAdviceDesc(adviceDesc);
						po2.setExecAddDesc(execAddDesc);
						//dao.addExecutePlan(po);
						
						dao.updateExecutePlan(po1,po2);
					//}
				//}
			}
				}
			//附件添加
			FileUploadManager.fileUploadByBusiness(campaignId, fjids, logonUser);
			
			act.setOutData("returnValue", 1);
			
		}
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.UPDATE_FAILURE_CODE,"活动方案下发");
			logger.error(logonUser,e1);
			act.setException(e1);
		}}
	}	
	
